package com.mystore.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mystore.Const;
import com.mystore.ServerResponse;
import com.mystore.user.mapper.UserMapper;
import com.mystore.user.pojo.User;
import com.mystore.user.service.IUserService;
import com.mystore.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liutl
 * @since 2019-05-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper mapper;

    @Override
    public ServerResponse<User> login(String username, String password) {
        QueryWrapper query = new QueryWrapper<>();
        query.eq("username", username);
        query.eq("password", MD5Util.MD5EncodeUtf8(password));
        User user = mapper.selectOne(query);
        if (user == null) {

            return ServerResponse.createBySuccessMessage("登录失败");

        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);


    }

    @Override
    public ServerResponse<User> register(User user) {

        ServerResponse validResponse = this.checkValid(user.getUsername(), Const.USERNAME);

        if (!validResponse.isSuccess()) {
            return validResponse;
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        mapper.insert(user);
        return ServerResponse.createBySuccessMessage("注册成功");
    }


    private ServerResponse checkValid(String str, String type) {

        if (StringUtils.isNotEmpty(type)) {

            if (Const.USERNAME.equals(type)) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("username", str);
                int isExist = mapper.selectCount(queryWrapper);
                if (isExist > 0) {
                    return ServerResponse.createByErrorMessage("用户名存在");
                }

            }

            if (Const.EMAIL.equals(type)) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("email", str);
                int isExist = mapper.selectCount(queryWrapper);
                if (isExist > 0) {
                    return ServerResponse.createByErrorMessage("email已经存在");
                }

            }
        } else {
            ServerResponse.createByErrorMessage("参数错误");
        }

        return ServerResponse.createBySuccessMessage("校验成功");
    }
}
